# -*- coding: utf-8 -*-
'''
@文件    :oss.py
@说明    :对象存储服务(Object Storage Service)
@时间    :2024/12/12 11:25:17
@作者    :浪晋
@版本    :1.0
'''

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client


class TencentOss(object):
    def __init__(self, SecretId, SecretKey, bucket, region, token=None, scheme="https"):
        self.SecretId = SecretId
        self.SecretKey = SecretKey
        self.bucket = bucket   # 例如 :abitof-1325810450
        self.region = region    # 例如: ap-chengdu
        self.token = token      # 例如: None
        self.scheme = scheme    # 例如: https
        
    def get_oss_client(self):
        config = CosConfig(Region=self.region, SecretId=self.SecretId, SecretKey=self.SecretKey, Token=self.token, Scheme=self.scheme)
        client = CosS3Client(config)
        return client

    def put_object(self,key: str, data):
        """文件流/字节流上传"""
        client = self.get_oss_client()
        response = client.put_object(
            Bucket=self.bucket,
            Body=data,   # 二进制数据
            Key=key # 例如: 2024/12/12/1.png
        )
        # url = client.get_object_url(self.bucket,key)
        url = f"https://{self.bucket}.cos.{self.region}.myqcloud.com/{key}" 
        return url


    def put_local_file(self,key: str, path: str):
        """本地文件上传"""
        client = self.get_oss_client()
        response = client.put_object_from_local_file(
            Bucket=self.bucket,
            LocalFilePath=path,   # 文件路径
            Key=key # 例如: 2024/12/12/1.png
        )
        # url = client.get_object_url(self.bucket,key)
        url = f"https://{self.bucket}.cos.{self.region}.myqcloud.com/{key}" 
        return url


    def object_exists(self, key: str):
        """判断对象是否存在"""
        client = self.get_oss_client()
        response  = client.object_exists(
            Bucket=self.bucket,
            Key=key
        )
        return response 
